<?php

namespace App\Think;

class Cache
{
    public static $instance;
    private $redisPool;

    static function init(...$args)
    {
        if(!isset(self::$instance)) self::$instance = new static(...$args);
        return self::$instance;
    }

    // public function __construct($opt = []) {
    //     $this->redisPool = \EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
    // }

    public function __clone(){}

    public function get($name, $default = false){
        return $this->exec(['act'=>'get', 'name'=>$name, 'default'=>$default]);
    }

    public function set($name, $value, $expire = null){
        return $this->exec(['act'=>'set', 'name'=>$name, 'value'=>$value, 'expire'=>$expire]);
    }

    public function exec($param){
        $redisPool = \EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();

        if($param['act'] == 'set'){
            $res = $redisPool->set($param['name'], $param['value'], $param['expire']);
        }
        if($param['act'] == 'get'){
            $res = $redisPool->get($param['name']);
            if(!$res) $res = $param['default'];
        }

        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redisPool);
        return $res;
    }


}
